package middleware

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"

	"recruit_student_backend/config"
)

// AuthMiddleware 验证用户认证状态的中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" || !validateToken(token) {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		token = strings.TrimPrefix(token, "Bearer ")
		secretKey := config.GetJWTConfig().SecretKey
		parsedToken, _ := jwt.ParseWithClaims(token, &jwt.RegisteredClaims{}, func(token *jwt.Token) (interface{}, error) {
			return secretKey, nil
		})
		if claims, ok := parsedToken.Claims.(*jwt.RegisteredClaims); ok {
			c.Set("jwt_claims", claims)
		}
		c.Next()
	}
}

// validateToken 验证令牌的有效性
func validateToken(token string) bool {
	token = strings.TrimPrefix(token, "Bearer ")

	// 从配置获取密钥
	secretKey := config.GetJWTConfig().SecretKey

	// 解析JWT令牌
	parsedToken, err := jwt.ParseWithClaims(token, &jwt.RegisteredClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("意外的签名方法: %v", token.Header["alg"])
		}
		return secretKey, nil
	})

	if err != nil {
		return false
	}

	// 验证令牌是否有效
	if claims, ok := parsedToken.Claims.(*jwt.RegisteredClaims); ok && parsedToken.Valid {
		// 检查令牌是否过期
		if claims.ExpiresAt != nil && claims.ExpiresAt.Time.Before(time.Now()) {
			return false
		}
		return true
	}

	return false
}
